package com.hbt.android.kotlin.service

import android.app.Notification
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi

/**
 * Service需要在AndroidManifext.xml中注册才能使用
 */
class LearnService2: Service() {

    private val TAG = "LearnService2"
    private var count = 0
    private var quit = false
    private val binder: MyBinder = MyBinder()

    /**
     * service被创建时调用
     */
    override fun onCreate() {
        super.onCreate()
        Log.e(TAG, "onCreate ->")
        // android大于8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notification = Notification.Builder(applicationContext, "channel_id").build()
            startForeground(1, notification)
        }

        Thread(Runnable {
            while (true) {
                if (quit) {
                    break
                }
                Thread.sleep(1000)
                count++
            }

        }).start()
    }



    inner class MyBinder:Binder() {
        fun getCount():Int {
            return count
        }
    }

    /**
     * 必须要实现的方法
     */
    override fun onBind(intent: Intent?): IBinder? {
        Log.e(TAG, "onBind ->")
        return binder
    }

    /**
     * Service被启动时调用， 如果多次调用startService，会直接调用onStartCommand
     */
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e(TAG, "onStartCommand ->")
        return super.onStartCommand(intent, flags, startId)
    }

    /**
     * 解除绑定
     */
    override fun onUnbind(intent: Intent?): Boolean {
        Log.e(TAG, "onUnbind ->")
        quit = true
        return super.onUnbind(intent)
    }

    /**
     * Service被关闭时调用
     */
    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy ->")
    }


}